package com.example.miniodownload.controller;

import com.example.miniodownload.service.MinioService;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.util.List;

@Controller
public class MainController {
    @FXML
    private TextField endpointField;
    @FXML
    private TextField accessKeyField;
    @FXML
    private PasswordField secretKeyField;
    @FXML
    private ComboBox<String> bucketComboBox;
    @FXML
    private TextField downloadPathField;
    @FXML
    private ProgressBar progressBar;
    @FXML
    private TextArea logArea;

    @Autowired
    private MinioService minioService;

    private volatile boolean isDownloading = false;
    private volatile int totalFiles = 0;
    private volatile int downloadedFiles = 0;

    @FXML
    private void handleConnect() {
        try {
            String endpoint = endpointField.getText().trim();
            String accessKey = accessKeyField.getText().trim();
            String secretKey = secretKeyField.getText().trim();

            if (endpoint.isEmpty() || accessKey.isEmpty() || secretKey.isEmpty()) {
                showAlert("错误", "请填写所有连接信息");
                return;
            }

            minioService.initializeMinioClient(endpoint, accessKey, secretKey);
            List<String> buckets = minioService.listBuckets();
            bucketComboBox.setItems(FXCollections.observableArrayList(buckets));
            if (!buckets.isEmpty()) {
                bucketComboBox.getSelectionModel().selectFirst();
            }

            showAlert("成功", "连接成功");
        } catch (Exception e) {
            showAlert("错误", "连接失败: " + e.getMessage());
        }
    }

    @FXML
    private void handleBrowse() {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("选择下载目录");
        File selectedDirectory = directoryChooser.showDialog(null);

        if (selectedDirectory != null) {
            downloadPathField.setText(selectedDirectory.getAbsolutePath());
        }
    }

    @FXML
    private void handleDownload() {
        if (isDownloading) {
            showAlert("提示", "下载正在进行中");
            return;
        }

        String selectedBucket = bucketComboBox.getValue();
        String downloadPath = downloadPathField.getText().trim();

        if (selectedBucket == null || selectedBucket.isEmpty()) {
            showAlert("错误", "请选择要下载的桶");
            return;
        }

        if (downloadPath.isEmpty()) {
            showAlert("错误", "请选择下载路径");
            return;
        }

        isDownloading = true;
        progressBar.setProgress(0);
        logArea.clear();

        new Thread(() -> {
            try {
                minioService.downloadBucket(selectedBucket, downloadPath, objectName -> {
                    Platform.runLater(() -> {
                        downloadedFiles++;
                        progressBar.setProgress((double) downloadedFiles / totalFiles);
                        logArea.appendText("下载: " + objectName + "\n");
                    });
                });

                Platform.runLater(() -> {
                    showAlert("成功", "下载完成");
                    isDownloading = false;
                });
            } catch (Exception e) {
                Platform.runLater(() -> {
                    showAlert("错误", "下载失败: " + e.getMessage());
                    isDownloading = false;
                });
            }
        }).start();
    }

    private void showAlert(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
}